#!/usr/bin/perl

##
## Copyright (C) 2008 Luciano Xumerle <luciano.xumerle@gmail.com>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

use strict;
use warnings;

my %genes = ();

open( FILE, $ARGV[0] ) || die "Give me a gff file please!\n\n";
while (<FILE>)
{
    chomp;
    my @a = split /\s/;

    next if ( $a[8] eq 'Gene' || $a[8] eq 'mRNA' );

    my $nome  = $a[9];
    my $chr   = $a[0];
    my $sense = $a[6];
    my $start = $a[3];
    my $stop  = $a[4];

    $genes{$nome}->{$start} = [ $stop, $chr, $sense ];

}
close FILE;

foreach my $gene ( keys %genes )
{
    my $lista = [];
    my $count = 0;
    foreach my $start ( sort { $a <=> $b } keys %{ $genes{$gene} } )
    {
        $count++;
        my $now = [
            $gene,                        $genes{$gene}->{$start}->[1],
            $genes{$gene}->{$start}->[2], $start,
            $genes{$gene}->{$start}->[0]
        ];
        push @$lista, $now;
    }

    my $esoni = $#$lista + 1;
    my $sense;
    my $chr;

    my @starts = ();
    my @stops  = ();

    foreach my $cur (@$lista)
    {
        $chr   = $cur->[1];
        $sense = $cur->[2];
        push @starts, $cur->[3] - 1;
        push @stops,  $cur->[4];
    }

    my $ss = join ',', @starts, '';
    my $ee = join ',', @stops,  '';

    print join "\t",
      (
        $gene, $chr, $sense, $starts[0], $stops[$#stops], $starts[0],
        $starts[0], $esoni, $ss, $ee, $gene, '.', '.'
      );
    print "\n";

}

